package com.twan.kotlinbase.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.widget.RadioButton
import butterknife.OnClick
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ToastUtils
import com.twan.kotlinbase.R
import com.twan.kotlinbase.alipay.PayResult
import com.twan.kotlinbase.app.BaseDataBindingActivity
import com.twan.kotlinbase.bean.OrderDTO
import com.twan.kotlinbase.databinding.ActivityPaytypeBinding
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.util.toFen
import com.twan.kotlinbase.util.toSafeFloat
import com.twan.xiaodulv.wxapi.WecahtPayUtils
import kotlinx.android.synthetic.main.activity_paytype.*
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

//支付方式
class PayTypeActivity : BaseDataBindingActivity<ActivityPaytypeBinding>(){
    lateinit var order: OrderDTO
    override fun getLayout(): Int {
        return R.layout.activity_paytype
    }

    override fun initEventAndData() {
        whiteStatusBar()
        title?.visibility= View.VISIBLE
        title?.text="支付方式"
        tv_right?.visibility = View.VISIBLE
        tv_right?.text=""
        order=intent.getSerializableExtra("order") as OrderDTO
        showUI()
    }

    fun showUI(){
        tv_amt.text=order.paymentAmount
        tv_amt1.text=order.paymentAmount
    }

//    @OnClick(R.id.rb_yue,R.id.rl_yue)
//    fun Rbyue(){
//        rb_yue.isChecked = true
//    }
//    @OnClick(R.id.rb_wechat,R.id.rl_wechat)
//    fun Rbwecaht(){
//        rb_wechat.isChecked= true
//    }
//    @OnClick(R.id.rb_zfb,R.id.rl_zfb)
//    fun Rbzfb(){
//        rb_zfb.isChecked= true
//        updatePayType(rb_zfb,rb_yue,rb_wechat)
//    }
//    fun updatePayType(rbview1:RadioButton,rbview2: RadioButton,rbview3: RadioButton){
//        if (rbview1.isChecked) {
//            rbview2.isChecked=false
//            rbview3.isChecked=false
//        }
//    }

    @OnClick(R.id.btn_ok)
    fun pay(){
        RxHttpScope().launch {
            if (rb_zfb.isChecked) {
                var req = RxHttp.postJson("aliPay/toPayAsMobile").add("orderId", order.id).add("totalAmount", order.paymentAmount).toResponse<String>().await()
                Thread {
                    var alipay = PayTask(mContext as Activity)
                    var result = alipay.payV2(req, true)
                    var msg = Message();
                    msg.what = 1
                    msg.obj = result
                    mHandler.sendMessage(msg)
                }.start()
            } else if (rb_wechat.isChecked){
                var req = RxHttp.postJson("wxPay/toPayAsMobile").add("orderId", order.id).add("totalAmount", (order.paymentAmount.toSafeFloat()*100f).toFen().toInt()).toResponse<WecahtPayUtils.WechatBean>().await()
                var bean = WecahtPayUtils.WechatBean();//后端请求的数据
                bean.appid = WecahtPayUtils.APP_ID;
                bean.partnerid = req.partnerid//"1521036471";
                bean.prepayid = req.prepayid//"wx21120101208173741eb1b562f323860000";
                bean.noncestr = req.noncestr//"2DACE78F80BC92E6D7493423D729448E";
                bean.timestamp = req.timestamp//"1603252875";
                bean.sign = req.sign//"7D7F24E2823171AF2FEE2BF691ED49A2";
                WecahtPayUtils.wxpay(mContext, bean)
            } else {
                var req = RxHttp.postJson("account/toPayAsBalance")
                        .add("extraPayByThird","0") //当使用余额支付，0全部为余额支付，1剩下的由支付宝支付，2剩下的由微信支付
                        .add("orderId", order.id)
                        .add("totalAmount", order.paymentAmount)
                    .toResponse<Any>().await()
                ToastUtils.showShort("余额成功")
            }
        }
    }

    //支付宝
    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付成功")
                        //Router.newIntent(this@AccessVipActivity).to(PaySuccessActivity::class.java).launch()
                        //this@AccessVipActivity.finish()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付失败")
                    }
                }
            }
        }
    }
}